package com.neuedu.mblog.controller;

import com.neuedu.mblog.dao.UploadFileDao;
import com.neuedu.mblog.entiry.UploadFile;
import com.neuedu.mblog.framework.Constants;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

/**
 * 项目：his
 * 创建时间：  2021/12/16   10:50
 * 作者 :jshand
 * 描述 : 下载
 *
 * /download?id=??
 */
@WebServlet(urlPatterns = "/download")
public class DownloadController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //给一个 文件的id，自己查询 文件的领
        String id = req.getParameter("id");
        UploadFile uploadFile = new UploadFileDao().selectById(Integer.parseInt(id));
        String path = uploadFile.getPath();


        resp.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(uploadFile.getOriginName(),"utf-8") +"");

        /**
         * id -- be17a954-81ee-4387-bfdd-8a498999fead.xls
         * "D:\\upload",be17a954-81ee-4387-bfdd-8a498999fead.xls
         *     读
         *     ↓
         *     发送到浏览器
         *
         */
        File downloadFile = new File(Constants.UPLOAD_BASE_DIR,path);
        InputStream is = new FileInputStream(downloadFile);
        ServletOutputStream os = resp.getOutputStream();
        //从文件中读取，写到浏览器
        byte[] bts = new byte[1024];
        int len = -1;
        while (   ( len =  is.read(bts) )  != -1        ){
            os.write(bts,0,len);
        }


        //关闭资源
        os.close();
        is.close();
    }
}
